<script setup>
import { ref, watch, onMounted, onBeforeUnmount, computed } from "vue";
import { useUserStore } from "@/store/modules/user";
import { likeVideoApi, unlikeVideoApi } from "@/api/like";
import { followUserApi, unfollowUserApi } from "@/api/follow";
import { createHistoryApi } from "@/api/history";
import { debounce } from "@/utils/index";
import { getVideoDetailApi } from "@/api/video";
import { useAuthGuard } from "@/hooks/useAuthGuard"; // 确保引入 useAuthGuard

import VideoPlayer from "@/components/VideoPlayer/VideoPlayer.vue";
import VideoInfo from "@/components/VideoPlayer/VideoInfo.vue";
import UserInfoAndCommentPanel from "@/components/UserInfoAndCommentPanel/index.vue";
import CollectionModal from "@/components/CollectionModal/index.vue";

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  videoId: {
    type: String,
    default: "",
  },
  video: {
    type: Object,
    default: () => ({}),
  },
});

// 获取身份验证守卫
const { authGuard } = useAuthGuard();

const emit = defineEmits(["close", "fullscreen", "details", "updateVideo"]);

const userStore = useUserStore();
const videoPlayerRef = ref(null);
const isPictureInPicture = ref(false);
const videoFit = ref("contain");
const showUserInfoAndCommentPanel = ref(false);
const showCollectionModal = ref(false);
const currentVideoId = ref(null);
const currentVideo = ref(null);
const isLoading = ref(false);

const initVideoData = async () => {
  if (!props.show) return;

  isLoading.value = true;
  console.log("开始加载视频数据:", currentVideoId.value);

  try {
    // 如果有videoId，直接从API加载
    if (currentVideoId.value) {
      console.log("从API加载视频:", currentVideoId.value);
      const response = await getVideoDetailApi(currentVideoId.value);

      if (response?.data) {
        const videoData = response.data;
        console.log("成功加载视频数据:", videoData.title);

        // 重新创建对象以避免引用问题
        currentVideo.value = {
          id: videoData.video_id || videoData.id,
          video_id: videoData.video_id || videoData.id,
          title: videoData.title,
          description: videoData.description || "暂无描述",
          src: videoData.oss_url,
          oss_url: videoData.oss_url, // 确保两种格式都有
          coverUrl: videoData.cover_url,
          cover_url: videoData.cover_url, // 确保两种格式都有
          likeCount: videoData.likeCount || 0,
          commentCount: videoData.commentCount || 0,
          favoritesCount: videoData.favoritesCount || 0,
          isLiked: videoData.isLiked || false,
          isFavorited: videoData.isFavorited || false,
          isFollowed: videoData.isFollowed || false,
          user: videoData.user
            ? {
                id: videoData.user.id,
                username: videoData.user.username || "未知用户",
                avatar: videoData.user.avatar || "",
              }
            : null,
        };
      } else {
        console.error("API返回的视频数据无效");
      }
    }
    // 如果没有获取到视频数据但有props.video，使用props.video
    else if (
      !currentVideo.value &&
      props.video &&
      (props.video.id || props.video.video_id)
    ) {
      console.log("使用props提供的视频对象:", props.video.title);

      // 确保ID统一
      const videoId = String(props.video.id || props.video.video_id);
      currentVideoId.value = videoId;

      // 创建新对象避免引用问题
      currentVideo.value = { ...props.video };
      currentVideo.value.id = videoId;
      currentVideo.value.video_id = videoId;
    } else {
      console.warn("无法加载视频数据：没有有效的视频ID或视频对象");
    }
  } catch (error) {
    console.error("加载视频详情失败:", error);
  } finally {
    isLoading.value = false;
  }
};

// 监听show和videoId变化，确保数据同步
watch(
  [
    () => props.show,
    () => props.videoId,
    () => props.video?.id || props.video?.video_id,
  ],
  async (
    [newShow, newVideoId, newVideoObjId],
    [oldShow, oldVideoId, oldVideoObjId]
  ) => {
    // 如果模态框处于显示状态且视频ID发生变化，重新加载视频
    if (
      newShow &&
      (newVideoId !== oldVideoId || newVideoObjId !== oldVideoObjId)
    ) {
      console.log("视频ID变化，重新加载:", newVideoId || newVideoObjId);
      currentVideoId.value = null; // 先清空当前ID，确保重新加载
      currentVideo.value = null; // 先清空当前视频对象，确保重新加载
      await initVideoData();
    }
  },
  { immediate: true }
);

watch(
  () => props.video,
  async (newVideo, oldVideo) => {
    // 只在模态框显示、有新视频且视频ID不同时重新加载
    if (
      props.show &&
      newVideo &&
      (!currentVideo.value ||
        (newVideo.id || newVideo.video_id) !==
          (currentVideo.value.id || currentVideo.value.video_id))
    ) {
      await initVideoData();
    } else if (props.show && newVideo && currentVideo.value) {
      // 仅更新视频的状态属性，而不是整个重新加载
      updateVideoState(newVideo);
    }
  },
  { deep: true }
);

// 添加一个更新视频状态的方法，不触发重新加载
const updateVideoState = (videoInfo) => {
  if (!currentVideo.value || !videoInfo) return;

  // 只更新状态相关的属性，而不是完全替换
  currentVideo.value = {
    ...currentVideo.value,
    likeCount:
      videoInfo.likeCount !== undefined
        ? videoInfo.likeCount
        : currentVideo.value.likeCount,
    commentCount:
      videoInfo.commentCount !== undefined
        ? videoInfo.commentCount
        : currentVideo.value.commentCount,
    favoritesCount:
      videoInfo.favoritesCount !== undefined
        ? videoInfo.favoritesCount
        : currentVideo.value.favoritesCount,
    isLiked:
      videoInfo.isLiked !== undefined
        ? videoInfo.isLiked
        : currentVideo.value.isLiked,
    isFavorited:
      videoInfo.isFavorited !== undefined
        ? videoInfo.isFavorited
        : currentVideo.value.isFavorited,
    isFollowed:
      videoInfo.isFollowed !== undefined
        ? videoInfo.isFollowed
        : currentVideo.value.isFollowed,
  };
};

// 关闭模态窗，重置状态
const closeModal = () => {
  // 如果正在画中画模式，先退出
  if (document.pictureInPictureElement) {
    document.exitPictureInPicture();
  }
  showUserInfoAndCommentPanel.value = false;
  showCollectionModal.value = false;
  // 重置视频数据，防止下次打开时显示旧数据
  currentVideo.value = null;
  emit("close");
};

// 进入全屏模式
const enterFullscreen = () => {
  emit("fullscreen");
};

// 点赞处理函数修改 - 使用防抖
const handleLike = debounce(async () => {
  authGuard(
    async () => {
      if (!currentVideo.value) return;

      // 记录之前的状态以便回滚
      const previousLikeState = currentVideo.value.isLiked;
      const previousLikeCount = currentVideo.value.likeCount;

      try {
        // 先更新本地状态，让用户立即看到反馈
        currentVideo.value.isLiked = !previousLikeState;
        currentVideo.value.likeCount += currentVideo.value.isLiked ? 1 : -1;

        // 调用相应的API
        if (currentVideo.value.isLiked) {
          await likeVideoApi(currentVideoId.value);
        } else {
          await unlikeVideoApi(currentVideoId.value);
        }

        // 向父组件通知视频状态更新，但不传递整个对象，只传递状态变化
        emit("updateVideo", {
          id: currentVideo.value.id || currentVideo.value.video_id,
          isLiked: currentVideo.value.isLiked,
          likeCount: currentVideo.value.likeCount,
        });
      } catch (error) {
        // 发生错误时恢复原状态
        console.error("点赞操作失败:", error);
        currentVideo.value.isLiked = previousLikeState;
        currentVideo.value.likeCount = previousLikeCount;
      }
    },
    {
      message: "登录后才能点赞视频",
    }
  );
}, 300);

// 打开评论面板
const handleComment = () => {
  authGuard(
    () => {
      showUserInfoAndCommentPanel.value = !showUserInfoAndCommentPanel.value;
      showCollectionModal.value = false; // 确保收藏面板关闭
    },
    {
      message: "登录后才能评论视频",
    }
  );
};

// 打开收藏面板
const handleFavorites = () => {
  authGuard(
    () => {
      // 阻止事件冒泡，防止触发视频模态框的关闭
      showCollectionModal.value = true;
      showUserInfoAndCommentPanel.value = false; // 确保评论面板关闭
    },
    {
      message: "登录后才能收藏视频",
    }
  );
};

// 处理收藏操作 - 添加更新事件
const handleCollect = async (selectedCollections) => {
  authGuard(
    async () => {
      if (!currentVideoId.value || selectedCollections.length === 0) return;

      try {
        console.log(
          `视频${currentVideoId.value}已添加到收藏夹:`,
          selectedCollections
        );

        // 更新视频的收藏状态
        currentVideo.value.isFavorited = true;

        currentVideo.value.favoritesCount += 1; // 模拟收藏数增加

        // 向父组件通知视频状态更新，只传递变化的部分
        emit("updateVideo", {
          id: currentVideo.value.id || currentVideo.value.video_id,
          isFavorited: true,
          favoritesCount: currentVideo.value.favoritesCount,
        });

        // 这里可以添加成功提示
        ElMessage && ElMessage.success("收藏成功");
      } catch (error) {
        console.error("处理收藏结果失败:", error);
      } finally {
        showCollectionModal.value = false;
      }
    },
    {
      message: "登录后才能收藏视频",
    }
  );
};

// 关注用户处理函数 - 使用防抖
const handleFollow = debounce(async () => {
  authGuard(
    async () => {
      if (!currentVideo.value || !currentVideo.value.user) return;

      const userId = currentVideo.value.user.id;
      const userName = currentVideo.value.user.username;
      const previousFollowState = currentVideo.value.isFollowed;

      try {
        // 调用相应的API
        if (!previousFollowState) {
          // 之前未关注，现在要关注
          const currentUserId = userStore.userInfo.id;
          await followUserApi(currentUserId, userId);
          ElMessage && ElMessage.success(`已关注 ${userName}`);
        } else {
          // 之前已关注，现在要取消关注
          const currentUserId = userStore.userInfo.id;
          await unfollowUserApi(currentUserId, userId);
          ElMessage && ElMessage.success(`已取消关注 ${userName}`);
        }

        // 更新关注状态
        currentVideo.value.isFollowed = !previousFollowState;
        // 向父组件通知视频状态更新，只传递变化的部分
        emit("updateVideo", {
          id: currentVideo.value.id || currentVideo.value.video_id,
          isFollowed: currentVideo.value.isFollowed,
        });
      } catch (error) {
        if (error.message === "不能关注自己") {
        } else {
          console.error("关注操作失败:", error);
          ElMessage && ElMessage.error("操作失败，请稍后重试");
        }
      }
    },
    {
      message: "登录后才能关注用户",
    }
  );
}, 300);

// 关闭评论面板
const closeUserInfoAndCommentPanel = () => {
  showUserInfoAndCommentPanel.value = false;
};

// 监听视频播放器的 fit 属性变化
const handleFitChange = (newFit) => {
  videoFit.value = newFit;
};

// 监听键盘事件，ESC关闭模态窗
const handleKeyDown = (event) => {
  if (event.key === "Escape" && props.show) {
    if (showUserInfoAndCommentPanel.value) {
      // 如果评论面板打开，先关闭评论面板
      showUserInfoAndCommentPanel.value = false;
    } else if (showCollectionModal.value) {
      // 如果收藏面板打开，先关闭收藏面板
      showCollectionModal.value = false;
    } else {
      closeModal();
    }
  }
};

// 添加评论数更新处理函数
const handleCommentUpdate = (count) => {
  if (!currentVideo.value) return;

  // 增加评论数量
  currentVideo.value.commentCount =
    (currentVideo.value.commentCount || 0) + count;

  // 向父组件通知视频状态更新
  emit("updateVideo", currentVideo.value);
};

// 修改处理切换视频的方法
const handleSwitchVideo = async (newVideo) => {
  if (!newVideo) return;

  const newVideoId = String(newVideo.id || newVideo.video_id);
  if (!newVideoId) return;

  console.log("接收到视频切换请求:", {
    id: newVideoId,
    title: newVideo.title || "未知标题",
    current: currentVideoId.value,
  });

  // 强制更新视频状态
  isLoading.value = true;

  // 先清除当前视频状态
  currentVideo.value = null;
  currentVideoId.value = null;

  try {
    // 发送更新请求到Store
    emit("updateVideo", {
      id: newVideoId,
      videoObj: newVideo,
    });

    // 更新当前视频ID
    currentVideoId.value = newVideoId;

    // 重新加载视频数据
    await initVideoData();
  } catch (error) {
    console.error("视频切换失败:", error);
  } finally {
    isLoading.value = false;
  }
};

// 组件挂载时添加事件监听
onMounted(() => {
  document.addEventListener("keydown", handleKeyDown);
});

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
  document.removeEventListener("keydown", handleKeyDown);
});

defineExpose({
  setVideoInfo(videoInfo) {
    currentVideo.value = videoInfo;
    currentVideoId.value = videoInfo.id;
  },
});
</script>

<template>
  <div class="video-modal-container" v-if="show">
    <div class="video-modal-overlay" @click="closeModal"></div>
    <div
      class="video-modal"
      :class="{ 'with-comment-panel': showUserInfoAndCommentPanel }"
    >
      <div class="modal-header">
        <h3>{{ currentVideo?.title }}</h3>
        <div class="modal-controls">
          <!-- <button class="control-button" @click.stop="togglePictureInPicture">
            <SvgIcon :icon-class="isPictureInPicture ? 'exit-pip' : 'pip'" :size="24" />
          </button> -->
          <button class="control-button" @click.stop="enterFullscreen">
            <SvgIcon icon-class="fullscreen" :size="24" />
          </button>
          <!-- <button class="control-button" @click.stop="goToDetails">
            <SvgIcon icon-class="details" :size="24" />
          </button> -->
          <button class="control-button close" @click.stop="closeModal">
            <SvgIcon icon-class="close" :size="24" />
          </button>
        </div>
      </div>

      <div class="modal-content">
        <div
          class="video-container"
          :class="{ shrink: showUserInfoAndCommentPanel }"
        >
          <!-- 添加加载状态显示 -->
          <div v-if="isLoading || !currentVideo" class="video-loading">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>
          <VideoPlayer
            v-if="currentVideo && currentVideo.src"
            ref="videoPlayerRef"
            :src="currentVideo?.src || ''"
            :poster="currentVideo?.coverUrl || ''"
            :autoplay="true"
            :muted="false"
            :loop="true"
            :controls="true"
            :is-active="true"
            :fit="videoFit"
            @update:fit="handleFitChange"
          >
            <VideoInfo
              :author="currentVideo?.user || {}"
              :description="currentVideo?.description || ''"
              :like-count="currentVideo?.likeCount || 0"
              :comment-count="currentVideo?.commentCount || 0"
              :favorites-count="currentVideo?.favoritesCount || 0"
              :is-like="currentVideo?.isLiked || false"
              :is-favorited="currentVideo?.isFavorited || false"
              :is-followed="currentVideo?.isFollowed || false"
              @like="handleLike"
              @comment="handleComment"
              @favorites="handleFavorites"
              @follow="handleFollow"
            />
          </VideoPlayer>
        </div>

        <!-- 评论面板 -->
        <UserInfoAndCommentPanel
          :show="showUserInfoAndCommentPanel"
          :video-id="currentVideoId"
          :video="currentVideo"
          @close="closeUserInfoAndCommentPanel"
          @follow="handleFollow"
          @commentUpdate="handleCommentUpdate"
          @switchVideo="handleSwitchVideo"
        />
      </div>
    </div>
    <!-- 收藏弹窗 -->
    <CollectionModal
      :show="showCollectionModal"
      :video-id="currentVideoId"
      @close="showCollectionModal = false"
      @collect="handleCollect"
    />
  </div>
</template>

<style scoped lang="scss">
.video-modal-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1001;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 1001;
}

.video-modal {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
  z-index: 1002;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;

  @media (max-width: 768px) {
    width: 100%;
    height: 100%;
    border-radius: 0;
  }

  // 添加评论面板显示时的样式
  &.with-comment-panel {
    .modal-content {
      display: flex;
      flex-direction: row;

      @media (max-width: 767px) {
        flex-direction: column;
      }
    }
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;

  h3 {
    margin: 0;
    font-size: 16px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .modal-controls {
    display: flex;
    gap: 8px;

    .control-button {
      background: none;
      border: none;
      color: white;
      cursor: pointer;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background-color 0.2s;

      &:hover {
        background-color: rgba(255, 255, 255, 0.2);
      }

      &.close:hover {
        background-color: rgba(255, 0, 0, 0.3);
      }
    }
  }
}

.modal-content {
  flex: 1;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  @media (min-width: 768px) {
    flex-direction: row;
  }
}

.video-container {
  flex: 1;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  width: 100%;
  height: 100%;

  @media (min-width: 768px) {
    &.shrink {
      width: calc(100% - 400px);
    }
  }

  @media (max-width: 767px) {
    &.shrink {
      height: 40%;
    }
  }
}

.video-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  z-index: 5;

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(0, 150, 255, 0.3);
    border-radius: 50%;
    border-top-color: #0096ff;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 12px;
  }

  p {
    font-size: 16px;
    color: #ffffff;
  }
}
</style>
